﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace SockLib.Device.ModbusDevices
{
   public  static  class ModBusDevice
    {

        static ModBusDevice()
        {
            Readconfig();
        }

        internal static readonly  string path = Directory.GetCurrentDirectory() + "\\Config\\ModBusDriver.xml";


        /// <summary>
        /// 读取配置
        /// </summary>
        static void Readconfig()
        {
            if (!Directory.Exists(Directory.GetCurrentDirectory() + "\\Config"))
                Directory.CreateDirectory(Directory.GetCurrentDirectory() + "\\Config");
            if (!File.Exists(path))
            {
                XDocument  xe = new XDocument();
                xe.Add(new XElement("ModBusDriver"));
                xe.Save(path);
            }
            else
            {
                try
                {
                    XElement XDoc = XElement.Load(path);
                    Write2Config(XDoc);
                }
                catch (Exception) { }  //文件载入失败或格式错误 
            }
        }

        /// <summary>
        /// 设备集合
        /// </summary>
        internal static List<ModBusCollection> MBCollections = new List<ModBusCollection>();
        /// <summary>
        /// 把xml中内容全部读出到MBCollections中
        /// </summary>
         static  void  Write2Config(XElement Doc)
        {
            var linq = from node in Doc.Elements ()
                       select node;
            foreach(XElement xe in linq )
            {
                ModBusCollection MB = new ModBusCollection();
                MB.Address = xe.Attribute("Address").Value ;
                foreach (XElement  gprs in xe.Elements()  )
                {
                    string gprsid = gprs.Attribute("Id").Value;
                    List<ModBusCollection.ModBusDevice> MBDevices = new List<ModBusCollection.ModBusDevice>();
                    foreach (XElement  device in gprs.Elements())
                    {
                        ModBusCollection.ModBusDevice MBDevice = new ModBusCollection.ModBusDevice();
                        MBDevice.DeviceID =Convert.ToInt32( device.Attribute("Id").Value);
                        MBDevice.Type   = Convert.ToInt32(device.Attribute("Type").Value);
                        MBDevices.Add(MBDevice);
                    }
                    MB.MBDevice.Add(gprsid, MBDevices);
                }
                MBCollections.Add(MB);

            }
                    
        }

        /// <summary>
        /// 把MBCollections中内存保存到xml文件中
        /// </summary>
        public static  void SaveConfig()
        {
            XElement doc = new XElement("ModBusDriver");
            foreach (ModBusCollection item in MBCollections)
            {
                XElement Server = new XElement("Server", new XAttribute("Address", item.Address));
                foreach (string  gprsid in item.MBDevice.Keys   )
                {
                    List<ModBusCollection.ModBusDevice> MBD = new List<ModBusCollection.ModBusDevice>();
                    MBD = item.MBDevice[gprsid];
                    XElement Gprs = new XElement("Gprs", new XAttribute("Id", gprsid));
                    foreach (ModBusCollection.ModBusDevice Device in MBD)
                    {
                        XElement De = new XElement("Device", new XAttribute("Id", Device.DeviceID), new XAttribute("Type",Device.Type ));
                        Gprs.Add(De);
                    }
                    Server.Add(Gprs);
                }
                doc.Add(Server);
            }
            doc.Save(path);
        }



        /// <summary>
        /// 保存设备编号对应的设备驱动到MBCollections中
        /// </summary>
        /// <param name="Address">ip地址</param>
        /// <param name="GprsId">GPRS编号</param>
        /// <param name="DeviceId">设备编号</param>
        /// <param name="DeviceType">设备类型</param>
        public static void SaveDevice(string Address,string GprsId,int DeviceId,int  DeviceType)
        {
            if (DeviceType == 0) return;
            ModBusCollection MBC = MBCollections.Where(p => p.Address == Address).FirstOrDefault ();
            if(MBC!=null )   //IP地址项存在
            {
                Dictionary<string, List<ModBusCollection.ModBusDevice>> DeviceList = MBC.MBDevice;
                if (DeviceList.ContainsKey(GprsId))  //GPRS项存在
                {
                    List<ModBusCollection.ModBusDevice> MBD = DeviceList[GprsId];
                    ModBusCollection.ModBusDevice item = MBD.Where(p => p.DeviceID == DeviceId).FirstOrDefault();
                    if (item != null )  //Device存在
                        item.Type = DeviceType;
                    else    //Device不存在
                    {
                        ModBusCollection.ModBusDevice MB = new ModBusCollection.ModBusDevice();
                        MB.DeviceID = DeviceId;
                        MB.Type = DeviceType;
                        MBD.Add(MB);
                    }
                }
                else  //GPRS不存在
                {
                    List<ModBusCollection.ModBusDevice> AMBD = new List<ModBusCollection.ModBusDevice>();
                    ModBusCollection.ModBusDevice Aitem = new ModBusCollection.ModBusDevice();
                    Aitem.DeviceID = DeviceId;
                    Aitem.DeviceID = DeviceType;
                    AMBD.Add(Aitem);
                    DeviceList.Add(GprsId, AMBD);
                }
            }
            else //IP地址项不存在
            {
                ModBusCollection BMBC = new ModBusCollection();
                BMBC.Address = Address;
                ModBusCollection.ModBusDevice BMBD = new ModBusCollection.ModBusDevice();
                BMBD.DeviceID = DeviceId;
                BMBD.Type = DeviceType;
                List<ModBusCollection.ModBusDevice> LBMBD = new List<ModBusCollection.ModBusDevice>();
                LBMBD.Add(BMBD);
                BMBC.MBDevice.Add(GprsId, LBMBD);
                MBCollections.Add(BMBC);
            }
        }

        /// <summary>
        /// 根据设备编号读取设备类型
        /// </summary>
        /// <param name="Address">ip地址</param>
        /// <param name="GprsId">GPRS编号</param>
        /// <param name="DeviceId">设备编号</param>
        /// <returns></returns>
        public static int GetDevice(string Address, string GprsId, int DeviceId)
        {
           ModBusCollection MB=  MBCollections.Where(p => p.Address == Address).FirstOrDefault();
            if (MB == null) return 0;
            if (!MB.MBDevice.ContainsKey(GprsId)) return 0;
            ModBusCollection.ModBusDevice MBD = MB.MBDevice[GprsId].Where(p => p.DeviceID == DeviceId).FirstOrDefault();
            if (MBD == null) return 0;
            return MBD.Type;
        }
    }

    public   class ModBusCollection
    {
        /// <summary>
        /// IP地址
        /// </summary>
        public   string  Address { get; set; }


        private   Dictionary<string,List<ModBusDevice>> _mbdevice=new Dictionary<string, List<ModBusDevice>>();
        /// <summary>
        /// 相同GPRS编号下的设备集合
        /// </summary>
        public   Dictionary<string,List<ModBusDevice>> MBDevice
        {
            get { return _mbdevice; }
            set { _mbdevice = value; }
        }

        /// <summary>
        /// 设备id对应的设备驱动
        /// </summary>
        public   class  ModBusDevice
        {
            /// <summary>
            /// 设备ID
            /// </summary>
           public  int  DeviceID;
            /// <summary>
            /// 设备类型
            /// </summary>
          public   int Type;
        }
    }

  
}
